package application.decryption;

import java.util.Vector;

import javax.swing.JTextArea;

import dao.TxtFileReader;

public class DecryptedInfo1 implements Decryption {
    public static final String FOLDING = "Folding";
    private TxtFileReader reader = new TxtFileReader();

    @Override
    public void log(JTextArea txtArea) {
        Vector<String> cipherLines = reader.readCiphers(FOLDING);
        int num = cipherLines.size();
        txtArea.append("Decrypting data in " + FOLDING + ".txt ...\n");
        for (String line : cipherLines) {
            line = line.trim();
            if (line.equals("")) {
                continue;
            }

            String[] s = line.split(" ");
            String lastName = decryptName(s[0]);
            String firstName = decryptName(s[1]);
            String code = decryptCode(s[2]);

            txtArea.append("Decrypted No." + num-- + " agent info: \n");

            txtArea.append("Decrypt first name from " + s[1] + " to " + firstName + "\n");
            txtArea.append("Decrypt last name from " + s[0] + " to " + lastName + "\n");
            txtArea.append("Decrypt agent code name from " + s[2] + " to " + code + "\n\n");
        }

        txtArea.append("All agent info in " + FOLDING + ".txt has been decrypted\n\n");
    }

    @Override
    public String decryptName(String cipher) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < cipher.length(); ++i) {
            char c = cipher.charAt(i);
            if (!Character.isAlphabetic(c)) {
                buffer.append(c);
                continue;
            }
            buffer.append('m' + 'n' - c);
        }

        return buffer.toString();
    }

    @Override
    public String decryptCode(String cipher) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < cipher.length(); ++i) {
            char c = cipher.charAt(i);
            if (!Character.isAlphabetic(c)) {
                buffer.append(c);
                continue;
            }

            buffer.append('5' + '6' - c);
        }

        return buffer.toString();
    }

}
